package com.consumer.handsome.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.consumer.handsome.domain.dto.UserLoginDto;
import com.consumer.handsome.domain.entity.UserEntity;
import com.consumer.handsome.exception.BussinessException;
import com.consumer.handsome.mapper.UserMapper;
import com.consumer.handsome.response.BaseResponse;

import com.consumer.handsome.utils.GetPassWord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Api(tags = "用户")
@Slf4j
public class UserController {
    @Autowired
    UserMapper userMapper;

    @ApiOperation(value = "注册操作",notes = "注册操作")
    @PostMapping("/org")
    public BaseResponse org(@RequestBody UserLoginDto userLoginDto){
        UserEntity username = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", userLoginDto.getUsername()));
        if (username!=null){
            throw new BussinessException("500","用户已存在，请重新创建用户");
        }
        UserEntity userEntity = new UserEntity();
        String md5PassWord = GetPassWord.getMd5PassWord(userLoginDto.getPassword(), userLoginDto.getUsername());
        userEntity.setPassword(md5PassWord);
        userEntity.setUsername(userLoginDto.getUsername());
        userMapper.insert(userEntity);
        return  BaseResponse.SUCCESS;
    }


    @ApiOperation(value = "登录操作",notes = "登录操作")
    @GetMapping("/login")
    public BaseResponse login(String username, String password){
        UserEntity userEntity = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", username));
        if (userEntity==null){
            throw new BussinessException("500","账户名错误，不存在这个用户");
        }
        String md5PassWord = GetPassWord.getMd5PassWord(password, username);
        log.info("newpassword===>"+md5PassWord);
        if (!userEntity.getPassword().equals(md5PassWord)){
            throw new BussinessException("500","密码错误");
        }
        return new BaseResponse(userEntity);
    }

    @GetMapping("/list")
    @ApiOperation(value = "用户列表")
    public BaseResponse getUserList(){
        return new BaseResponse(userMapper.selectList(new QueryWrapper<UserEntity>()));
    }

    @GetMapping("/{id}")
    public BaseResponse getByOne(@PathVariable int id){
        return new BaseResponse<>(userMapper.selectById(id));
    }

    @DeleteMapping("/{id}")
    public BaseResponse deleteByOne(@PathVariable int id){
        return new BaseResponse<>(userMapper.deleteById(id));
    }

}
